import promisePool from './Pool.js'

export default class CategoryDao {

    static async insert (category) {
        let connection = null
        try {
            connection = await promisePool.getConnection()
        
            let result = await connection.query('insert into `category` (`name`) values (?)', category.name)

            return result[0].affectedRows
        } catch (error) {
            return error
        } finally {
            if (connection) connection.release()
        }
    }

    static async delete (category) {
        let connection = null
        try {
            connection = await promisePool.getConnection()

            let result = await connection.query('delete from `category` where `id` = ?', category.id)

            return result[0].affectedRows
        } catch (error) {
            return error
        } finally {
            if (connection) connection.release()
        }
    }

    static async update (category) {
        let connection = null
        try {
            connection = await promisePool.getConnection()

            let result = await connection.query('update `category` set `name` = ? where `id` = ?', [category.name, category.id])

            return result[0].affectedRows
        } catch (error) {
            return error
        } finally {
            if (connection) connection.release()
        }
    }

    static async selectById (id) {
        let connection = null
        try {
            connection = await promisePool.getConnection()

            let result = await connection.query('select `id`, `name` from `category` where `id` = ?', id)

            return result[0]
        } catch (error) {
            return error
        } finally {
            if (connection) connection.release()
        }
    }

    static async selectByLimit (start, end) {
        let connection = null
        try {
            connection = await promisePool.getConnection()

            let result = await connection.query('select `id`, `name` from `category` limit ?, ' + end, start)

            return result[0]
        } catch (error) {
            return error
        } finally {
            if (connection) connection.release()
        }
    }

    static async selectCount () {
        let connection = null
        try {
            connection = await promisePool.getConnection()

            let result = await connection.query('select count(id) as total from `category`')

            return result[0][0]
        } catch (error) {
            return error
        } finally {
            if (connection) connection.release()
        }
    }
}